package com.gdchent.rn.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.util.Log;

import com.gdchent.rn.bean.ProductInfo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class DbHelper extends SQLiteOpenHelper {

  private static final String DB_NAME = "product_db";
  private static final String TABLE_NAME = "product_table";

  private static DbHelper dbHelper;
  public Context context;
  private SQLiteDatabase database;
  public static DbHelper getInstance(Context context) {

    if (dbHelper == null) {
      dbHelper = new DbHelper(context, DB_NAME, null, 1);
    }
    return dbHelper;
  }

  private DbHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
    super(context, name, factory, version);
    this.context = context;
    Log.i("gdchentbbbbb", "DbHelper_constructor");
    this.database=getWritableDatabase();
    dropTable();
    readCSV2();
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
    Log.i("gdchentbbbbb", "DbHelper_onCreate");
       testC();

  }

  private void testC() {
  }

  private void readCSV2() {
    //File file = new File("file://///android_asset/data.csv");
    //Log.i("gdchentbbbbb", file.getAbsolutePath());
    BufferedReader br = null;
    String line = "";
    String everyLine = "";
    int i = 0;
    try {
      //br = new BufferedReader(new FileReader(file));
      InputStream inputStream = context.getAssets().open("data.csv");
      br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
      List<String> allString = new ArrayList<>();
      String category_name="";
      while ((line = br.readLine()) != null) // 读取到的内容给line变量
      {
        if (i == 0) {
          line = line.replaceAll(" ", "_");//将空格转为下划线
          System.out.println("第一行：" + line);
          createTable(); //创建表
        } else {
          // 如果是第0个
          everyLine = line;
          System.out.println(everyLine);
          ProductInfo productInfo = new ProductInfo();
          String arr[] = everyLine.split(",");
          if(i==1){
             category_name=arr[0];
          }//如果当前category_name等于表中的category_name

          productInfo.setCategory_name(arr[0]);
          productInfo.setProduct_name(arr[1]);
          productInfo.setPrice(Double.parseDouble(arr[2]));
          productInfo.setQuantity(Long.parseLong(arr[3]));
          productInfo.setImage_file(arr[4]);
          insertData(productInfo); //插入数据库
          allString.add(everyLine);
        }
        i++;
      }
      System.out.println("csv表格中所有行数：" + allString.size());
    } catch (IOException e) {
      e.printStackTrace();
    }finally {
      selectDataList();
    }
  }


  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

  }

  /**
   * 创建数据库表
   *
   *
   */
  private void createTable() {
    if(database==null){
      database = getWritableDatabase();
    }
    String createTableSql = "create table if not exists " + TABLE_NAME + "(id Integer primary key," +
      " category_name varchar(128),product_name varchar(128),price double(8, 2),quantity bigInt(12) ,image_file varchar(256));";
    try {
        database.execSQL(createTableSql);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * 删除数据库表
   */
  public void dropTable() {
    if(database==null){
      database = getWritableDatabase();
    }
    String dropSql = "drop table if exists " + TABLE_NAME;
    try {
      database.execSQL(dropSql);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void insertData(ProductInfo productInfo) {
    try {
      ContentValues contentValues = new ContentValues();
      contentValues.clear();
      contentValues.put("category_name", productInfo.getCategory_name());
      contentValues.put("product_name", productInfo.getProduct_name());
      contentValues.put("price", productInfo.getPrice());
      contentValues.put("quantity", productInfo.getQuantity());
      contentValues.put("image_file", productInfo.getImage_file());
      database.insert(TABLE_NAME, null, contentValues);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public List<ProductInfo> selectDataList() {
    Cursor cursor = null;
    List<ProductInfo> productInfoList = new ArrayList<>();
    try {
      if(database!=null){
        database.close();
      }
      if(database==null){
        database= getReadableDatabase();
      }
      String[] columns = new String[]{"category_name", "product_name", "price", "quantity","image_file"};
      cursor = database.query(TABLE_NAME, columns, null, null, null, null, null);
      if (cursor != null) {
        //游标不为空
        System.out.println("游标不为空 开始读取数据");
        while (cursor.moveToNext()) {
          String category_name = cursor.getString(cursor.getColumnIndex("category_name"));
          String product_name = cursor.getString(cursor.getColumnIndex("product_name"));
          double price = cursor.getDouble(cursor.getColumnIndex("price"));
          Long quantity = cursor.getLong(cursor.getColumnIndex("quantity"));
          String image_file = cursor.getString(cursor.getColumnIndex("image_file"));
          ProductInfo productInfo = new ProductInfo();
          productInfo.setCategory_name(category_name);
          productInfo.setProduct_name(product_name);
          productInfo.setPrice(price);
          productInfo.setQuantity(quantity);
          productInfo.setImage_file(image_file);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (cursor != null) {
        cursor.close();
      }
    }
    return productInfoList;
  }

  /**
   * 清楚表的数据
   */
  public void cleanUpData() {
    SQLiteDatabase database = getWritableDatabase();
    String cleanUpDataSql = "delete from " + TABLE_NAME;
    try {
      database.execSQL(cleanUpDataSql);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

}
